-- loads spritesheet
-- allows to draw sprites

local Sprites = {isInitialized = false}


-- localpath - path to the spritesheet image
-- datapath - path to the data about sprites in the spritesheet
function Sprites.load(localpath, datapath)

    if Sprites.isInitialized then
        return
    end


    if not localpath or not datapath then
        error("No arguments were given!")
    end


    print("Loading spritesheet \"" .. localpath .. 
        "\" with settings at \"" .. datapath .. "\"")


    Sprites.spritesheet = love.graphics.newImage(localpath)

    local spritesheetData = io.open(datapath, 'r')
    local TileSize = tonumber(spritesheetData:read())

    print("Tile size " .. TileSize)

    -- parse spritesheet info
    -- the format is:
    -- tilename xoffset yoffset
    -- one per line for each tile that
    -- will be registered
    for line in spritesheetData:lines() do
        name, ox, oy = string.match(line, '(.+)%s+(%d+)%s+(%d+)')
        ox = tonumber(ox)
        oy = tonumber(oy)

        Sprites[name] = love.graphics.newQuad(ox, oy, TileSize, TileSize,
            Sprites.spritesheet:getWidth(), Sprites.spritesheet:getHeight())

        print(string.format('Loaded tile "%s" at offset (%d,%d)', name, ox, oy))
    end

    spritesheetData:close()
    Sprites.isInitialized = true
    print("Done initializing sprites!")
end


-- just like love.graphics.draw(image, quad, ...), but
-- substitutes image and quad automatically
function Sprites.draw(name, ...)
    if not Sprites.isInitialized then
        error("Attempt to use uninitialized spritesheet!")
    end

    love.graphics.draw(Sprites.spritesheet, Sprites[name], ...)
end


return Sprites